<!--
使用方法：
    //引入
    import ImportExcel from "@common/components/import/excel.vue";

    //默认模式
    <ImportExcel :option="importOption" @postImport="handleImportData" />
    // @postImport //点击导入按钮调用方法

    //配置项
    downloadFile: '', //下载模板名称 必填
    configFile: '',//导入模板配置名称 必填
    uploadedShowData: false,//读取成功后是否立即显示数据 默认false
    importBtnText: '导 入',//导入按钮文字
    closeBtnText: '关 闭',//关闭按钮文字

    //显示导入窗口
    showImportExcelDialog() {
        let $this = this;
        $this.importOption = {
            visible: true,
            downloadFile: '工程报价核算表.xlsx',
            configFile: 'SalePricingDetail.xml',
        };
    },
    //具体处理导入数据的方法
    handleImportData(data) {
        let _this = this;
        baseRelatedPartyApi.importSysClient({list:data.list}, () => {
            _this.$message.success("导入成功");
            _this.$refs['commonImportExcelDialog'].closeDialog();
            _this.getList();
        },(res) => {
            _this.$refs['commonImportExcelDialog'].enableImportBtn();
            _this.$refs['commonImportExcelDialog'].showErrorMsg(res.message);
            _this.$message.error(res.message);
        });
    },
-->
<template>
    <div class="import_dialog_container">
        <el-dialog class="import_dialog" :title="optionData.title"
                   :visible.sync="optionData.visible"
                   :width="optionData.width" :append-to-body="optionData.appendToBody"
                   :before-close="optionData.handleClose" v-dialogDrag>
            <div class="dialog_content">
                <el-form ref="userPwForm" label-width="110px">
                    <el-form-item label="上传文件" style="margin-bottom: 0;">
                        <el-upload class="import_upload upload-demo" ref="importUpload"
                                   :class="{'manual_upload': !autoUpload}"
                                   :action="fileApiUrl.uploadFile" :auto-upload="autoUpload"
                                   :headers="{token: token,account_set_sid:account_set_sid}" :show-file-list="false"
                                   :data="{bizPath: 'temp', biz_type: 'import'}"
                                   :limit="1" accept=".xls,.xlsx"
                                   :before-upload="handleBeforeUpload"
                                   :on-change="handleUploadChange"
                                   :on-success="handleUploadSuccess">
                            <el-input type="text" v-model="optionData.fileName" placeholder="点击选择上传文件" readonly
                                      @click.native="handleClickUpload"/>
                        </el-upload>
                        <el-button class="submit_upload" type="success" @click="submitUpload"
                                   v-if="!autoUpload">上传
                        </el-button>
                    </el-form-item>
                    <el-form-item label="最后忽略行数" style="margin-bottom: 0;" v-if="false">
                        <el-input type="text" v-model="optionData.lastRowSkipQty" placeholder="点击选择上传文件"/>
                    </el-form-item>
                    <el-form-item style="margin-bottom: 0;" v-if="optionData.error">
                        <span style="color: red;">{{optionData.errorMsg || ''}}</span>
                        <el-link type="danger" style="line-height: 1.5;" @click="handleDownloadError">请点击下载查看</el-link>
                    </el-form-item>
                    <el-form-item style="margin-bottom: 5px;" v-if="optionData.success">
                        <span style="color: #67C23A;margin-right: 10px;">读取Excel成功，行数：{{importData.list.length}}</span>
                        <el-link type="primary" style="line-height: 1.5;" @click="handleShowImportList" v-if="!showImportDetail && !optionData.uploadedShowData">查看数据</el-link>
                    </el-form-item>
                    <el-form-item style="margin-bottom: 5px;" v-if="optionData.import_error">
                        <span
                            style="color: red;margin-right: 10px;">导入失败：{{ optionData.import_msg }}</span>
                    </el-form-item>
                    <el-row v-if="optionData.success && (showImportDetail || optionData.uploadedShowData)">
                        <el-col :span="24">
                            <vxeTableTemplate :data="importList" :options.sync="tableOptions"/>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="handleDownloadTemplate" v-if="$utils.isNotEmpty(optionData.downloadFile)">下载模板</el-button>
                <el-button @click="optionData.visible = false">{{optionData.closeBtnText}}</el-button>
                <el-button type="primary" @click="handleClickConfirm" :disabled="optionData.disable_import_btn">{{optionData.importBtnText}}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import fileApi from "@common/api/fileApi";
    import poiApi from "@common/api/poiApi";

    export default {
        name: "ImportExcelDialog",
        props: {
            option: {
                type: Object,
                default () {
                    return {};
                },
            },
            autoUpload: {
                type: Boolean,
                default: true,
            },
        },
        data () {
            return {
                excelContentType: ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
                fileApiUrl: fileApi.url,
                token: this.$store.state.accessToken.token,
                account_set_sid:this.$utils.getAccountSetSid(),
                optionData: {},
                defaultOption: {
                    visible: false,
                    title: '上传',
                    width: '600px',
                    appendToBody: false,
                    fileName: '',
                    handleClose (done) {
                        done();
                    },
                    success: false,
                    error: false,
                    errorMsg: '',
                    errorFile: '',
                    import_error: false,
                    import_msg: '',
                    lastRowSkipQty: 0,
                    downloadFile: '', //下载模板名称 必填
                    configFile: '',//导入模板配置名称 必填
                    uploadedShowData: false,//读取成功后是否立即显示数据 默认false
                    importBtnText: '导 入',//导入按钮文字
                    closeBtnText: '关 闭',//关闭按钮文字
                    disable_import_btn:true,
                },
                showImportDetail: false,
                importData: {},
                tableOptions: {
                    ref: 'ShowImportDataTable',
                    columns: [],
                    pagination: false,
                    hideIndex: true,
                    getMaxHeight() {
                        return 450;
                    },
                },
                importList: [],
            };
        },
        watch: {
            option: {
                handler () {
                    this.init();
                },
                deep: true,
            },
        },
        mounted () {
            this.init();
        },
        methods: {
            init () {
                this.showImportDetail = false;
                if (this.option.visible && !this.$scopedSlots.content) {
                    // if (!this.$utils.isNotEmpty(this.option.downloadFile)) {
                    //     this.$message.error('缺少配置：downloadFile');
                    //     return;
                    // }
                    if (!this.$utils.isNotEmpty(this.option.configFile)) {
                        this.$message.error('缺少配置：configFile');
                        return;
                    }
                }
                this.optionData = $.extend({}, this.defaultOption, this.option);
            },
            disableImportBtn(){
                this.optionData.disable_import_btn = true;
            },
            enableImportBtn(){
                this.optionData.disable_import_btn = false;
            },
            showErrorMsg(msg){
                if (msg){
                    this.optionData = $.extend(this.optionData,{import_error:true,import_msg:msg});
                }else{
                    this.optionData = $.extend(this.optionData,{import_error:false,import_msg:''});
                }
            },
            showDialog(options) {
                this.optionData = $.extend({}, this.optionData, {
                    success: false,
                    error: false,
                    import_error:false,
                    disabledImportBtn:true,
                });
                this.showImportDetail = false;
                this.optionData = $.extend({}, this.defaultOption, options);
            },
            closeDialog(){
                this.optionData = $.extend({}, this.optionData, {
                    visible:false,
                });
            },
            handleBeforeUpload (file) {
                let bol = true;
                if (this.excelContentType.indexOf(file.type) === -1) {
                    this.$message.error('请选择Excel文件');
                    return !bol;
                }

                this.$emit('beforeUpload', file, function callback(res) {
                    if (!res) {
                        bol = false;
                    }
                });

                return bol;
            },
            handleUploadChange (file, fileList) {
                this.optionData = $.extend({}, this.optionData, {
                    fileName: file.name,
                });
            },
            submitUpload () {
                this.$refs.importUpload.submit();
            },
            handleClickUpload () {
                this.$refs.importUpload.clearFiles();
            },
            handleUploadSuccess (res) {
                let _this = this;
                if (res.data) {
                    poiApi.readExcel(res.data.sid, _this.optionData.configFile, _this.optionData.lastRowSkipQty).then(result => {
                        let resData = result.data || {};
                        _this.importData = $.extend({}, resData);
                        _this.optionData = $.extend({}, _this.optionData, {
                            success: true,
                            error: false,
                            import_error:false,
                            disable_import_btn:false,
                        });
                        _this.$emit('retData', resData.list);
                        if (_this.showImportDetail || _this.optionData.uploadedShowData) {
                            _this.handleShowImportList();
                        }
                    }).catch(err => {
                        _this.importData = $.extend({}, err);
                        _this.optionData = $.extend({}, _this.optionData, {
                            success: false,
                            error: true,
                            errorMsg: err.message,
                            errorFile: err.data,
                            list: [],
                        });
                        _this.importList = [];
                    });
                }
            },
            handleDownloadTemplate () {
                if (this.$utils.isNotEmpty(this.optionData.downloadFile)) {
                    let link = document.createElement('a');
                    link.href = poiApi.getDownloadUrl(this.optionData.downloadFile) + '?t=' + ((new Date()).getTime());
                    link.download = this.optionData.downloadFile;
                    link.click();
                    document.body.removeChild(link);
                }
            },
            handleDownloadError () {
                if (this.$utils.isNotEmpty(this.optionData.errorFile)) {
                    let link = document.createElement('a');
                    link.href = this.fileApiUrl.getFile + this.optionData.errorFile;
                    link.download = this.optionData.downloadFile;
                    link.click();
                    document.body.removeChild(link);
                }
            },
            handleShowImportList() {
                let columns = this.importData.excelFileTitles.filter(item => {
                        return item.hide === false;
                });
                columns = columns.map(item => {
                    return {
                        label: item.title,
                        prop: item.fieldName,
                        align: 'center',
                    };
                });
                this.tableOptions = $.extend({}, this.tableOptions, {
                    columns,
                });
                this.importList = [].concat(this.importData.list || []);
                this.showImportDetail = true;
            },
            handleClickConfirm() {
                this.showErrorMsg(null);
                this.disableImportBtn();
                this.$emit('postImport', this.importData, this.optionData);
            },
        },
    }
</script>

<style lang="less" rel="stylesheet/less">
    .import_dialog {
        .import_upload {
            display: inline-block;
            vertical-align: top;
            width: 100%;
            line-height: 1;

            .el-upload--text {
                width: 100%;
                height: auto;
                border: none;

                /deep/ .el-input__inner {
                    cursor: pointer;
                }
            }
        }

        .manual_upload {
            width: calc(100% - 61px);
        }

        .submit_upload {
            display: inline-block;
            vertical-align: top;
        }
        .el-dialog__footer .el-button {
             margin-right: 2em;
         }
    }
</style>
